<template>
  <main-content title="会员权益">
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" clearable placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <goods-supplier-filter url="merchant/member/goods/getStore"
            @change="({ selected }) => searchForm.storeId = selected"></goods-supplier-filter>
          <el-form-item>
            <el-button type="primary" @click="refreshList">查询</el-button>
            <el-button type="primary" @click="addGoods" v-has="['10100201']">新增商品</el-button>
            <el-button type="primary" @click="goConfigureGiftPack" v-has="['10100202']">新增礼品包</el-button>
            <!-- TODO 加权限 -->
            <el-button type="primary" @click="showExportData = true">导出</el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <goods-list ref="goodsListRef" table-url="/merchant/member/goods/pageProduct" :table-param="{...searchForm,goodsIds:goodsIds}"
      product-list-url="/merchant/member/goods/getGoodsProducts" @click-edit="goEdit" @click-delete="handleGoodsRowDelete"
      @click-stock-manage="showEditStock" @click-add-product="handleAddProduct" @click-product-edit="showEditProduct"
      @click-product-delete="handleProductRowDelete" :edit-goods-permission="['10100203']"
      :stock-manage-permission="['10100204']" :add-product-permission="['10100205']"
      :delete-goods-permission="['10100206']" :edit-product-permission="['10100207']"
      :delete-product-permission="['10100208']"></goods-list>

    <!--    新增商品，选择商品新增-->
    <select-goods v-model:show="isShowSelectGoods" table-url="/merchant/member/goods/pageStoreProduct"
      :table-param="tableParams" @select="handleGoodsSelectNext"
      ref="selectGoodsRef"
      >
      <template #search>
        <el-tabs
        v-model="selectForm.defaultStore"
        class="demo-tabs"
      >
        <el-tab-pane
          name="0"
          label="商户商家供货"
        />
        <el-tab-pane
          name="1"
          label="联海供货"
        />
      </el-tabs>
        <!-- <search-bar inline> -->
          <!-- <template #normal> -->
          <el-form :model="selectForm" inline ref="selectFormRef">
            <el-form-item label="商品名称">
              <el-input v-model="selectForm.name" placeholder="请输入商品名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
            <el-cascader :options="merchantCategory" :props="props1" clearable @change="productTypeChange" />
          </el-form-item>
          <el-form-item label="商家名称">
            <el-select
              v-model="storeIds"
              placeholder="请选择商家"
              clearable
            >
              <el-option
                v-for="(item) in supplierList"
                :key="item.id"
                :label="item.storeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="input-range-box">
            <el-form-item label="供货价" style="margin-right:12px" label-width="68px" 
             prop="minCost" :rules="rules.minAmount">
              <el-input style="width: 200px;" v-model="selectForm.minCost" placeholder="请输入最低金额" clearable></el-input>
            </el-form-item>
            <el-form-item  prop="maxCost" :rules="rules.maxAmount">
              <template #label>
                <span>~</span>
              </template>
              <el-input style="width: 200px;" v-model="selectForm.maxCost" placeholder="请输入最高金额" clearable></el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
            <!-- <goods-supplier-filter url="merchant/member/goods/getStore"
              @change="({ selected }) => selectForm.storeIds = [selected]">
            </goods-supplier-filter> -->
          <!-- </template> -->
        
        <!-- </search-bar> -->
      </template>
    </select-goods>

    <!--    编辑商品-->
    <edit-goods v-model:show="isShowEditGoods" :row-data="currentEditingRow"
      submit-url="merchant/member/goods/updateGoods" @confirm="refreshList"></edit-goods>

    <!--    编辑库存-->
    <edit-stock v-model:show="isShowEditStock" :row-data="currentStockEditingRow"
      :column-props="['addOrDeductionStockCount']" products-url="merchant/member/goods/getGoodsProducts"
      submit-url="merchant/member/goods/saveOrUpdateProduct" @confirm="refreshList"></edit-stock>

    <!--    新增规格-->
    <add-product v-model:show="isShowAddProduct" :row-data="currentGoodsRowForAddProduct"
      :form-props="['name', 'thumbnailUrl', 'addOrDeductionCount', 'payOfCurrencyCount', 'payPrice']"
      submit-url="merchant/member/goods/saveOrUpdateProduct"
      store-products-url="merchant/member/goods/getStoreGoodsDetail" @confirm="refreshList"></add-product>

    <!--    编辑规格-->
    <edit-product v-model:show="isShowEditProduct" :row-data="currentGoodsRowForEditProduct"
      :product-row-data="currentProductRowForEditProduct" submit-url="merchant/member/goods/saveOrUpdateProduct"
      :form-props="['name', 'thumbnailUrl', 'addOrDeductionCount']" @confirm="refreshList"></edit-product>

    <!--      编辑礼品包-->
    <edit-gift-pack v-model:show="isShowEditGiftPack" :row-data="currentGiftPackEditingRow" @confirm="handleEditGiftPack">
    </edit-gift-pack>

    <!--      编辑礼品包库存-->
    <edit-stock v-model:show="isShowEditGiftPackStock" :row-data="currentStockEditingRow"
      :column-props="['addOrDeductionStockCount']" products-url="merchant/member/goods/giftPackProducts"
      submit-url="merchant/member/goods/saveOrUpdateProduct" @confirm="refreshList">
    </edit-stock>

    <!--    新增礼品包规格-->
    <add-gift-pack-product v-model:show="isShowAddGiftPackProduct" :row-data="currentAddGiftPackProductRow"
      :store-row-data="currentAddGiftPackProductStoreRow" @confirm="handleAddGiftPackProduct">

    </add-gift-pack-product>
    <exportData v-model:show-dialog="showExportData" :search-data="searchForm" title="会员权益"
      export-type="memberProductExport">
    </exportData>
  </main-content>
</template>
<script lang="ts">
export default {
  name: 'Benefits'
}
</script>
<script lang="ts" setup>
import GoodsList from "@/components/goodsCenter/GoodsList.vue"
import SelectGoods from "@/components/goodsCenter/SelectGoods.vue"
import EditGiftPack from "./components/EditGiftPack.vue"
import { useGoodsSelect } from "@/components/goodsCenter/compositions/useGoodsSelect";
import { useEditGoods } from "@/components/goodsCenter/compositions/useEditGoods";
import { useEditStock } from "@/components/goodsCenter/compositions/useEditStock";
import { useAddProduct } from "@/components/goodsCenter/compositions/useAddProduct";
import { useEditProduct } from "@/components/goodsCenter/compositions/useEditProduct";
import { useDeleteProduct } from "@/components/goodsCenter/compositions/useDeleteProduct";
import { useDeleteGoods } from "@/components/goodsCenter/compositions/useDeleteGoods";
import { IGoodsPageRow, IStoreGoodsPageRow, IStoreProductRow } from "@/api/modules/pointsMall";
import { useEditGiftPack } from "@/components/goodsCenter/compositions/useEditGiftPack";
import { IGiftPackGoodsEntity, IUpdateGiftPackData } from "@/api/modules/vipCenter";
import { addGiftProduct, deleteGiftPack, deleteGoods, updateGiftPack,getMerchantCategoryApi,getSupplierApi } from "@/api/vipCenter";
import { Ref } from "vue";
import AddGiftPackProduct from "@/views/vipCenter/components/AddGiftPackProduct.vue";
import { ElMessageBox } from "element-plus";
import exportData from "@/components/exportData/exportData.vue";
import { useCrossPage } from "@/compositions/crossPage/useCrossPage";
import { debounceUtils } from "@/utils/index.js";
// TODO 测试删除商品 删除礼品包
// 新增商品 选择商品
const { isShowSelectGoods, showGoodSelect, selectForm, handleSelect } = useGoodsSelect()
const router = useRouter()
const showExportData = ref(false)
const store = useStore();
// 表格渲染
const goodsListRef = ref()
const storeIds = ref<string>()
watch(storeIds, (newVal) => {
  selectForm.storeIds = newVal === '' || newVal === undefined ? [] : [newVal]
})
const tableParams=ref({ 
  productName: '',
  storeId: null,
  withProducts: true,
  minCost:null,
  maxCost:null
})
// 搜索表单
const searchForm = reactive({
  productName: '',
  storeId: null,
  withProducts: true,
})
const selectGoodsRef=ref()
const selectFormRef=ref()
const rules={
  minAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(selectForm.maxCost&&+value>selectForm.maxCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }
  ],
  maxAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(selectForm.minCost&&+value<selectForm.minCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }]
}
const searchList=debounceUtils(()=>{
  selectGoodsRef.value.search()
},800)
watch(selectForm,()=>{
  selectFormRef.value?.validate((valid:boolean)=>{
    if(valid){
      tableParams.value=Object.assign({},selectForm)
      tableParams.value.minCost=selectForm.minCost?(selectForm.minCost*100):null
      tableParams.value.maxCost=selectForm.maxCost?(selectForm.maxCost*100):null
      searchList()
    }
  })
})
watch(isShowSelectGoods,(val)=>{
  if(!val){
    selectFormRef.value?.resetFields()
  }
})

//通知跳转参数
const goodsIds=computed(()=>{
  return store.state.memberStore.goodsIds.filter(Boolean)
})
const route=useRoute()
watch(()=>route.params,(val)=>{
  if(val){
    searchForm.productName=val.goodsName||''
  }
},{immediate:true})

watch(searchForm,()=>{
  store.commit("memberStore/setGoodsIds", [])
})

watch(goodsIds,()=>{
    let timer=setTimeout(() => {
      clearTimeout(timer)
      refreshList()
    }, 100);
})

const props1 = {
checkStrictly: true,
value:'id',
  label:'categoryName'
}
const productTypeChange=(value:any)=>{
  if(value.length){
    selectForm.categoryId=value[value.length-1]
  }else{
    selectForm.categoryId=''
  }
  
}
const refreshList = () => {
  goodsListRef.value?.refreshList()
}



// 编辑商品
const { isShowEditGoods, showEditGoods, currentEditingRow } = useEditGoods()

// 删除商品
const handleDeleteGoods = async (row: IGoodsPageRow) => {
  const rs = await deleteGoods({ id: row.id })
  if (rs.code === 200) {
    ElMessage.success('删除成功')
    refreshList()
  }
}

// 编辑库存
const { isShowEditStock, isShowEditGiftPackStock, showEditStock, currentStockEditingRow } = useEditStock()

// 新增规格
const { isShowAddProduct, showAddProduct, currentGoodsRowForAddProduct } = useAddProduct()

// 编辑规格
const {
  isShowEditProduct, showEditProduct,
  currentGoodsRowForEditProduct, currentProductRowForEditProduct
} = useEditProduct()

// 删除规格
const { handleProductDelete } = useDeleteProduct()

// 编辑礼品包
const { isShowEditGiftPack, currentGiftPackEditingRow, showEditGiftPack } = useEditGiftPack()
const handleEditGiftPack = async (formattedForm: IUpdateGiftPackData) => {
  const rs = await updateGiftPack(formattedForm)

  if (rs.code === 200) {
    ElMessage.success('保存成功')
    refreshList()
  }
}

// 删除礼品包
const handleDeleteGiftPack = async (rowData: IGoodsPageRow) => {
  const rs = await deleteGiftPack({ id: rowData.id })
  if (rs.code === 200) {
    ElMessage.success('删除成功')
    refreshList()
  }
}

// 新建礼品包
const goConfigureGiftPack = () => {
  router.push('configure_gift_pack')
}

// 礼品包新增规格
const isShowAddGiftPackProduct: Ref<boolean> = ref(false)
const currentAddGiftPackProductStoreRow: Ref<IStoreGoodsPageRow | undefined> = ref()
const showAddGiftPackProduct = (rowData: IStoreGoodsPageRow) => {
  currentAddGiftPackProductStoreRow.value = rowData
  isShowAddGiftPackProduct.value = true
}
const handleAddGiftPackProduct = async (form: IGiftPackGoodsEntity) => {
  // console.log('handleAddGiftPackProduct', form)
  isShowAddGiftPackProduct.value = false
  const rs = await addGiftProduct(form)

  if (rs.code === 200) {
    ElMessage.success('添加成功')
    refreshList()
  }
}


// 商品选择器相关
let goodsSelectNextHandler: (rowData: IStoreGoodsPageRow) => void = (rowData: IStoreGoodsPageRow) => { }
const handleGoodsSelectNext = (rowData: IStoreGoodsPageRow) => {
  // debugger
  isShowSelectGoods.value = false
  goodsSelectNextHandler(rowData)
}
// 添加商品 -- 显示商品选择器 -- 跳转到编辑商品页
const addGoods = () => {
  goodsSelectNextHandler = handleSelect
  showGoodSelect()
  getMerchantCategory();
  getSupplier()
}
// 礼品包商品行 添加 规格 -- 显示商品选择器 -- 显示添加 礼品包规格弹窗
const currentAddGiftPackProductRow: Ref<IGoodsPageRow | undefined> = ref()
const addProductForGiftPack = (rowData: IGoodsPageRow) => {
  currentAddGiftPackProductRow.value = rowData
  goodsSelectNextHandler = showAddGiftPackProduct
  showGoodSelect()
}

// 商品大行 编辑
const goEdit = (row: IGoodsPageRow) => {
  if (row.type === 'pack') {
    // 礼品包
    showEditGiftPack(row)
  } else {
    // 商品
    showEditGoods(row)
  }
}

// 商品大行新增规格
const handleAddProduct = (rowData: IGoodsPageRow) => {
  if (rowData.type === 'pack') {
    // 礼品包
    addProductForGiftPack(rowData)
  } else {
    // 商品
    showAddProduct(rowData)
  }
}

// 商品大行 删除
const handleGoodsRowDelete = (row: IGoodsPageRow) => {
  ElMessageBox.confirm('确定删除？', '提示').then(() => {
    if (row.type === 'pack') {
      // 礼品包
      handleDeleteGiftPack(row)
    } else {
      // 商品
      handleDeleteGoods(row)
    }
  }).catch(() => {
    // cancel
  })
}

// 规格删除
const handleProductRowDelete = (productRow: IStoreProductRow, goodsRow: IGoodsPageRow) => {
  ElMessageBox.confirm('确定删除？', '提示').then(() => {
    if (goodsRow.type === 'pack') {
      console.log('点击了礼品包的删除, TODO 接口确认')
      handleProductDelete('merchant/member/goods/delProduct', productRow, goodsRow, goodsListRef)
    } else {
      handleProductDelete('merchant/member/goods/delProduct', productRow, goodsRow, goodsListRef)
    }
  }).catch(() => {
    // cancel
  })
}
const merchantCategory=ref([]);
const supplierList=ref([]);
// 获取分类
const getMerchantCategory = async () => {
  const rs = await getMerchantCategoryApi({ defaultStore:selectForm.defaultStore })
  if (rs.code === 200) {
    merchantCategory.value=rs.payload;
  }
}
const getSupplier = async () => {
  const rs = await getSupplierApi({ defaultStore:selectForm.defaultStore })
  if (rs.code === 200) {
    supplierList.value=rs.payload;
  }
}
// keepAlive 导致的刷新问题
useCrossPage("vipCenter", { refreshList })

// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    // 待完善
    refreshList();
  },
  {
    deep: true
  }
)

watch(() => selectForm.defaultStore, (val) => {
  if (val) {
    selectForm.name='';
    selectForm.storeIds=[];
    selectForm.categoryId='';
    storeIds.value=''
    getMerchantCategory();
    getSupplier()
  }
}, {deep:true});

//新增礼品包返回数据刷新
onActivated(()=>{
  refreshList()
})
</script>

<style scoped lang="scss">
  :deep(.el-cascader) {
    .el-input .el-input__suffix-inner .el-icon {
      &::before {
        display: none;
      }
    }
  }
</style>
